package com.ruoyi.system.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.constant.Constants;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.TaskSubAllMapper;
import com.ruoyi.system.mapper.TaskTypeMapper;
import com.ruoyi.system.utils.OutStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.AllTaskMapper;
import com.ruoyi.system.service.IAllTaskService;


import static com.ruoyi.system.utils.DirectoryUtil.copyFolder;
import static com.ruoyi.system.utils.DirectoryUtil.deleteDirectory;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-24
 */
@Service
public class AllTaskServiceImpl implements IAllTaskService
{
    @Autowired
    private AllTaskMapper allTaskMapper;

    @Autowired
    private TaskSubAllMapper taskSubAllMapper;
    @Autowired
    private TaskTypeMapper taskTypeMapper;
    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public AllTask selectAllTaskById(Long id)
    {
        return allTaskMapper.selectAllTaskById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param allTask 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<AllTask> selectAllTaskList(AllTask allTask)
    {
        return allTaskMapper.selectAllTaskList(allTask);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param allTask 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertAllTask(AllTask allTask)
    {
        return allTaskMapper.insertAllTask(allTask);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param allTask 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateAllTask(AllTask allTask)
    {
        return allTaskMapper.updateAllTask(allTask);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAllTaskByIds(Long[] ids)
    {
        return allTaskMapper.deleteAllTaskByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteAllTaskById(Long id)
    {
        return allTaskMapper.deleteAllTaskById(id);
    }

    @Override
    public AllTask gettaskid(Long typeId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        AllTask allTask = allTaskMapper.getAllTask(userId,typeId);
        if(allTask==null){
            allTask = new AllTask();
            allTask.setUserId(userId);
            Long status = 0L;
            allTask.setStatus(status);
            LocalDateTime currentTime = LocalDateTime.now();
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 将当前时间格式化为字符串
            String formattedTime = currentTime.format(formatter);
            allTask.setOverTime(formattedTime);
            allTask.setTypeId(typeId);
            allTaskMapper.insertAllTask(allTask);
            return allTask;
        }
        return allTask;
    }


    @Override
    public boolean addtasksub(Long taskId,List<String> sublist,String folder,String baseFolder){
        File parentFolder = new File(folder);
        File[] subdirectories = parentFolder.listFiles(File::isDirectory);
        String subfolder = subdirectories[0].getName();//第一层子目录
        File parentFolder2 = new File(folder+File.separator+subfolder);
        File[] subdirectories2 = parentFolder2.listFiles(File::isDirectory);

        TaskSubAll taskSubAlltemp = new TaskSubAll();
        taskSubAlltemp.setTaskId(taskId);
        List<TaskSubAll> taskSubAlls = taskSubAllMapper.selectTaskSubAllList(taskSubAlltemp);
        List<String> sublisttemp = new ArrayList<>();
        for(TaskSubAll taskSubAll:taskSubAlls){
            sublisttemp.add(taskSubAll.getSubname());
        }
        for(int i=0;i<subdirectories2.length;i++){
            if(sublisttemp.contains(subdirectories2[i].getName())){
                return false;
            }
        }
        String directoryPath = baseFolder+File.separator+taskId;

        // 创建 File 对象
        File directory = new File(directoryPath);
        // 判断文件夹是否存在
        if (!directory.exists()) {
            // 尝试创建文件夹
            directory.mkdirs(); // 使用 mkdirs() 可以创建多级目录
        }


        Path sourceDir = Paths.get(folder+File.separator+subfolder);
        Path targetDir = Paths.get(directoryPath);
        Path DeleteDir = Paths.get(folder);
        try {
            //复制源文件夹及其所有子文件夹和文件到目标文件夹
            //删除文件夹
            copyFolder(sourceDir, targetDir);
            deleteDirectory(DeleteDir);
        } catch (IOException e) {
            e.printStackTrace();
        }

        for(String subname:sublist){
            TaskSubAll taskSubAll = new TaskSubAll();
            taskSubAll.setTaskId(taskId);
            taskSubAll.setSubname(subname);
            taskSubAllMapper.insertTaskSubAll(taskSubAll);
        }
        return true;
    }

    @Override
    public void updateAlltaskstatus(Long id) {
        AllTask allTask = allTaskMapper.selectAllTaskById(id);
        Long typeId = allTask.getTypeId();
        int status234 = allTaskMapper.select234status(typeId);
        TaskType taskType = taskTypeMapper.selectTaskTypeById(typeId);
        int maxqueue = Math.toIntExact(taskType.getMaxqueue());
        if(status234>= maxqueue){
            int queue = allTaskMapper.selectmaxqueue(typeId);
            allTask.setStatus(1l);
            allTask.setQueue(Long.valueOf(queue+1));
            allTaskMapper.updateAllTask(allTask);
        }
        else {
            allTask.setStatus(2l);
            allTask.setQueue(0l);
            allTaskMapper.updateAllTask(allTask);
        }
    }

    @Override
    public void updatemanytaskstatus() {
        TaskType taskType = new TaskType();
        List<TaskType> taskTypes = taskTypeMapper.selectTaskTypeList(taskType);
        for(TaskType t:taskTypes){
            Long typeId = t.getId();
            int status234 = allTaskMapper.select234status(typeId);
            int maxqueue = Math.toIntExact(t.getMaxqueue());
            if(status234<maxqueue){
                AllTask allTask = new AllTask();
                allTask.setStatus(1l);
                List<AllTask> allTasks = allTaskMapper.selectAllTaskList(allTask);
                for(AllTask allTask1:allTasks){
                    Long que = allTask1.getQueue()-1;
                    if(que!=0){
                        allTask1.setQueue(que);
                        allTaskMapper.updateAllTask(allTask1);
                    }
                    else {
                        allTask1.setQueue(que);
                        allTask1.setStatus(2l);
                        allTaskMapper.updateAllTask(allTask1);
                    }
                }
            }
        }
    }




}
